﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GolfLeague.Models
{
    public class HandicapInterface
    {
        GolfLeagueEntities golfDB = new GolfLeagueEntities();

        public IQueryable<HandicapCalculation> GetAllHandicapCalculations()
        {
            return from handicapEntity in golfDB.HandicapCalculations
                   orderby handicapEntity.HandicapName
                   select handicapEntity;
        }

        public HandicapCalculation GetHandicapCalculation(int handicapCalculationID)
        {
            return (from handicapEntity in golfDB.HandicapCalculations
                    where handicapEntity.HandicapCalculationID.Equals(handicapCalculationID)
                    select handicapEntity).FirstOrDefault();
        }

        public PlayerHandicap GetHandicap(int handicapID)
        {
            return (from handicapEntity in golfDB.PlayerHandicaps
                    where handicapEntity.HandicapID.Equals(handicapID)
                    select handicapEntity).FirstOrDefault();
        }

        public PlayerHandicap GetCurrentHandicap(int playerID)
        {
            return (from handicapEntity in golfDB.PlayerHandicaps
                    where handicapEntity.PlayerID.Equals(playerID)
                    orderby handicapEntity.CreatedOn descending
                    select handicapEntity).FirstOrDefault();
        }

        public PlayerHandicap GetPreviousHandicap(int playerID)
        {
            var prevHandicap = from handicapEntity in golfDB.PlayerHandicaps
                               where handicapEntity.PlayerID.Equals(playerID)
                               orderby handicapEntity.CreatedOn descending
                               select handicapEntity;

            return (prevHandicap.Count() > 1 ? prevHandicap.ElementAt(1) : null);
        }

        public void AddHandicap(PlayerHandicap playerHandicap)
        {
            golfDB.PlayerHandicaps.AddObject(playerHandicap);
        }

        public void Save()
        {
            golfDB.SaveChanges();
        }
    }
}